import { useRequest } from 'ahooks';
import { countBy, map, uniq, uniqBy } from 'lodash-es';
import { PropsWithChildren, useContext, useEffect } from 'react';
import React, { createContext, useState } from 'react';

import { apiCardsListByGet } from '@/application/apis/cards';
import { apiGoodsHasStockByGet } from '@/application/apis/goods';
import { apiTaskReachCardsByGet, apiTaskUnFinishedCountByGet } from '@/application/apis/task';
import { useGlobal } from '@/application/context/global';
import { useUser } from '@/application/hooks/use-user';
import { DialogContent } from '@/components/Dialog';
import { ActivityFinishedQueryDto, Cards } from '@/types/apiType';

import { CardDialog } from './components/CardDialog';

interface HomeContextValue {
  [key: string]: any;
  cardList?: Cards[];
  reachCardInfo?: ActivityFinishedQueryDto & {
    uniqWin: string[];
    formatWin: { id: number; num: number }[];
    goodStock?: boolean;
  };
  taskUnFinished?: number;
}

export const HomeContext = createContext<HomeContextValue>({});

/**
 * 用户状态上下文
 *
 * 并且会将用户状态持久化在localStorage中
 */
export const HomeProvider: React.FC<PropsWithChildren> = ({ children }) => {
  // 任务列表
  const [showTask, setShowTask] = useState(false);
  // 分享sheet
  const [showShareActionSheet, setShowShareActionSheet] = useState(false);
  const { goodInfo, activityInfo } = useGlobal();
  const { user } = useUser();
  useEffect(() => {
    if (goodInfo?.id && user?.token) {
      refreshCard();
      refreshData();
    }
  }, [goodInfo, user]);

  const refreshData = () => {
    refreshHasCard();
    refreshTaskUnFinished();
  };
  const { data: cardList, refresh: refreshCard } = useRequest(
    () => apiCardsListByGet({ goodsId: goodInfo?.id as number }),
    {
      manual: true
    }
  );

  const [reachCardInfo, setReachCardInfo] = useState<HomeContextValue['reachCardInfo']>();

  const { refresh: refreshHasCard } = useRequest(
    () =>
      apiTaskReachCardsByGet({
        goodsId: goodInfo?.id as number,
        activityId: activityInfo?.id as number
      }),
    {
      onSuccess: async (res) => {
        const arr = (res?.winCards || '').split(',').filter(Boolean);
        const count = countBy(arr);
        const result = map(count, (num, id) => ({ id: parseInt(id), num }));
        let goodStock = true;
        try {
          if (!res?.received) {
            goodStock = (await apiGoodsHasStockByGet({
              goodsId: goodInfo?.id as number,
              activityId: activityInfo?.id as number
            })) as unknown as boolean;
          }
        } catch (e) {
          console.log('e');
        }

        setReachCardInfo({
          ...res,
          goodStock,
          uniqWin: uniq(arr),
          formatWin: result
        });
      },
      manual: true
    }
  );

  const { data: taskUnFinished, refresh: refreshTaskUnFinished } = useRequest(
    () =>
      apiTaskUnFinishedCountByGet({
        goodsId: goodInfo?.id as number,
        activityId: activityInfo?.id as number
      }),
    { manual: true }
  );
  const loginCheck = (callback: () => void) => {
    if (!user?.m1Status) {
      return CardDialog.show({
        children: <DialogContent title="无法参与活动" subTitle="您暂不符合活动参与条件哦" />
      });
    }
    callback();
  };

  const homeValue = {
    showTask,
    setShowTask,
    showShareActionSheet,
    setShowShareActionSheet,
    loginCheck,
    cardList,
    reachCardInfo,
    taskUnFinished,
    refreshData
  };

  return <HomeContext.Provider value={homeValue}>{children}</HomeContext.Provider>;
};

/**
 * 当前用户状态
 */
const useHome = () => useContext(HomeContext);
export { useHome };
